﻿using System;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using umbraco.cms.businesslogic.datatype;
using umbraco.interfaces;

namespace Eksponent.CropUp.Umbraco
{
    public class CropperPrevalueEditor : WebControl, IDataPrevalue
    {
        private readonly BaseDataType _dataType;

        public CropperPrevalueEditor(BaseDataType dataType)
        {
            _dataType = dataType;           
        }



        private HtmlInputText _fileProperty;
        private Label _filePropertyLabel;

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            _filePropertyLabel = new Label {Text = "File property alias"};
            _fileProperty = new HtmlInputText();

            _filePropertyLabel.AssociatedControlID = _fileProperty.ID = "FilePropertyName";
            Controls.Add(_filePropertyLabel);
            Controls.Add(_fileProperty);
        }

        public string ImageProperty
        {
            get
            {
                var prevalues = PreValues.GetPreValues(_dataType.DataTypeDefinitionId);
                return prevalues.Count > 0 ? ((PreValue)prevalues[0]).Value : "umbracoFile";
            }
        }



        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            _fileProperty.Value = ImageProperty;
        }

        public void Save()
        {
            var prevalues = PreValues.GetPreValues(_dataType.DataTypeDefinitionId);
            if (prevalues.Count > 0)
            {
                var pv = (PreValue)prevalues[0];
                pv.Value = _fileProperty.Value;
                pv.Save();
            }
            else
            {
                PreValue.MakeNew(_dataType.DataTypeDefinitionId, _fileProperty.Value);
            }
        }

        public Control Editor
        {
            get { return this; }
        }
    }
}
